from PyQt4.QtGui import QWidget
from PyQt4 import QtCore,QtGui
import pyqtgraph as pg
from KModel.KSingleStock import KSingleStock

## The only required methods are paint() and boundingRect() 
## (see QGraphicsItem documentation)
class KChartPriceDisplayItem(pg.GraphicsObject):
	def __init__(self, stockobject):
		pg.GraphicsObject.__init__(self)
		self.m_stock=stockobject # maintain a stock object inside of each item,which is the data source of this display item
		self.PrepareRenderPicture()

	def PrepareRenderPicture(self):
		## pre-computing a QPicture object allows paint() to run much more quickly, 
		## rather than re-drawing the shapes every time.
		priceblocks=self.m_stock.CurWindowData('Price')
		XCordinates=self.m_stock.CurWindowData('Index')

		self.picture = QtGui.QPicture()
		p = QtGui.QPainter(self.picture)
		p.setPen(pg.mkPen('w'))
		width=1.0/3.0
		for index in range(0,len(priceblocks)):
			(openp,highp,lowp,closep,vol)=priceblocks[index]
			xcord=XCordinates[index]
			p.drawLine(QtCore.QPointF(xcord, lowp), QtCore.QPointF(xcord, highp))
			if openp > closep:
				p.setBrush(pg.mkBrush('r'))
			else:
				p.setBrush(pg.mkBrush('g'))
			p.drawRect(QtCore.QRectF(xcord-width,openp,width*2, closep-openp))
		p.end()
	def ChangePeriod(self,period):
		self.m_stock.ChangePeriod(period)
		self.UpdateDisplay()
		
	def UpdateDisplay(self):
		self.PrepareRenderPicture() #regenerate the picture
		self.update(self.boundingRect()) # update this item
		self.informViewBoundsChanged() # inform its viewbox to update,otherwise the viewbox related can't update(like axis)		
		
	def paint(self, p, *args):
		p.drawPicture(0, 0, self.picture)


	def boundingRect(self):
		## boundingRect _must_ indicate the entire area that will be drawn on
		## or else we will get artifacts and possibly crashing.
		## (in this case, QPicture does all the work of computing the bouning rect for us)
		return QtCore.QRectF(self.picture.boundingRect())
